package com.avantis.admin.service.impl;

import com.avantis.admin.service.LevelService;
import com.avantis.common.base.BaseServiceImpl;
import com.avantis.common.entity.Level;
import com.avantis.common.entity.query.LevelQuery;
import com.avantis.common.exception.ServiceProcessException;
import com.avantis.common.repository.LevelRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
* @Description:    java类作用描述
* @Author:         kirago
* @CreateDate:     2019/2/16 3:02 PM
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
@Service
@Transactional
public class LevelServiceImpl extends BaseServiceImpl<LevelRepository, Level> implements LevelService {

    @Autowired
    private LevelRepository levelRepository;

    @Autowired
    private LevelService levelService;

    @Override
    public void saveLevel(Level level) {
        try{
            save(level);
        } catch (ServiceProcessException e) {
            throw e;
        } catch (Exception e) {
            throw new ServiceProcessException("新增等级失败！");
        }
    }

    @Override
    public Page<Level> findLevelCriteria(LevelQuery levelQuery) {
        Pageable pageable = new PageRequest(levelQuery.getPageNumber()-1,levelQuery.getPageSize());
        Page<Level> levelPage = levelRepository.findAll(new Specification<Level>() {

            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
                return criteriaQuery.getRestriction();
            }
        },pageable);

        return levelPage;
    }

    @Override
    public void modifyLevel(Level level) {
        levelRepository.saveAndFlush(level);
    }

    @Override
    public void deleteLevel(String levelId) {
        levelRepository.deleteByUuid(levelId);
    }

    @Override
    public List<Level> findCustomerLevels(Integer levelType) {
        return levelRepository.findAllByLevelType(levelType);
    }
}
